<template>
    <el-card class="box-card">
        <template #header>
            <div class="card-header">
                <span>轮播图管理</span>
                <span>
                    <el-button @click="add()" type="success" plain>
                        <el-icon>
                            <CirclePlus />
                        </el-icon>
                        添加轮播图
                    </el-button>
                </span>
            </div>
        </template>
        <el-table :data="datas">
            <el-table-column width="40" label="#" prop="id" />
            <el-table-column label="链接标题" prop="title" />
            <el-table-column label="轮播图片" prop="picture">
                <template #default="scope">
                    <el-image style="width: 180px; height: 60px" :src="scope.row.picture" />
                </template>
            </el-table-column>
            <el-table-column label="跳转地址" prop="url" width="250" />
            <el-table-column label="跳转方式" prop="target" />
            <el-table-column label="排序数字" prop="slide_order">
                <template #default="scope">
                    <el-button size="small" type="primary" plain>
                        {{scope.row.slide_order}}
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column label="状态" prop="slide_order">
                <template #default="scope">
                    <el-tag :type="color(scope.row.usable)">
                        {{text(scope.row.usable)}}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column width="100" label="添加日期" prop="create_time" />
            <el-table-column width="300" label="操作">
                <template #default="scope">
                    <el-button @click="edit(scope.$index)" type="primary" plain>
                        <el-icon>
                            <EditPen />
                        </el-icon>编辑
                    </el-button>
                    <el-button @click="open(scope.row.id,scope.row.usable)" :type="openColor(scope.row.usable)" plain>
                        <el-icon>
                            <EditPen />
                        </el-icon>启用
                    </el-button>
                    <el-button @click="remove(scope.row.id)" type="danger" plain>
                        <el-icon>
                            <Delete />
                        </el-icon> 删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-card>
    <!-- 添加轮播图-->
    <el-dialog v-model="AddDialogTable" title="添加轮播图" align-center>
        <template #default="scope">
            <el-form :rules="rules" :model="form">
                <el-form-item label="轮播图片" prop="name">
                    <el-upload class="avatar-uploader" action="http://localhost:3001/upload/common/"
                        :show-file-list="false" :headers="headers" accept=".jpeg,.png,.jpg" :data="extra"
                        :on-success="handleAvatarSuccess" :on-error="handleUploadError"
                        :before-upload="handleBeforeUpload">
                        <img v-if="form.picture" :src="form.picture" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="标题文字" prop="title">
                    <el-input v-model="form.title" />
                </el-form-item>
                <el-form-item label="链接地址" prop="url">
                    <el-input v-model="form.url" placeholder="http://" />
                </el-form-item>
                <el-form-item label="跳转方式" prop="target">
                    <div class="mb-2 flex items-center text-sm">
                        <el-radio-group v-model="form.target" class="ml-4">
                            <el-radio label="_blank" size="large">新窗口跳转</el-radio>
                            <el-radio label="_self" size="large">本窗口跳转</el-radio>
                        </el-radio-group>
                    </div>
                    <!-- <el-input v-model="form.target" /> -->
                </el-form-item>
                <el-form-item label="显示顺序" prop="slide_order">
                    <el-input v-model="form.slide_order" />
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="AddDialogTable = false">取消</el-button>
                <el-button @click="saveAdd()" type="primary">保存</el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 编辑轮播图-->
    <el-dialog v-model="dialogTableVisible" title="编辑轮播图" align-center :data="form">
        <template #default="scope">
            <el-form>
                <el-form-item label="轮播图片" prop="name">
                    <el-upload class="avatar-uploader" action="http://localhost:3001/upload/common/"
                        :show-file-list="false" :headers="headers" accept=".jpeg,.png,.jpg" :data="extra"
                        :on-success="handleAvatarSuccess" :on-error="handleUploadError"
                        :before-upload="handleBeforeUpload">
                        <img v-if="form.picture" :src="form.picture" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="标题文字" prop="name">
                    <el-input v-model="form.title" />
                </el-form-item>
                <el-form-item label="链接地址" prop="url">
                    <el-input v-model="form.url"/>
                </el-form-item>
                <el-form-item label="跳转方式" prop="target">
                    <div class="mb-2 flex items-center text-sm">
                        <el-radio-group v-model="form.target" class="ml-4">
                            <el-radio label="_blank" size="large">新窗口跳转</el-radio>
                            <el-radio label="_self" size="large">本窗口跳转</el-radio>
                        </el-radio-group>
                    </div>
                    <!-- <el-input v-model="form.target" /> -->
                </el-form-item>
                <el-form-item label="显示顺序" prop="name">
                    <el-input v-model="form.slide_order" />
                </el-form-item>
            </el-form>
        </template>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogTableVisible = false">取消</el-button>
                <el-button @click="save()" type="primary">保存</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup>
import { ref, reactive } from 'vue';
import popular from '@/api/popular';
let datas = ref([])
let form = ref({});
async function loadList() {
    let { status, msg, data } = await popular.slide();
    if (status) {
        datas.value = data;
    } else {
        ElMessage(msg);
    }
}
loadList();
let color = (usable) => {
    if (usable === 1) return 'success';
    return 'error';
}
let openColor = (usable) => {
    if (usable === 1) return 'info';
    return 'success';
}
let text = (usable) => {
    if (usable === 1) return '开启';
    return '关闭';
}
let open = async (id, usable) => {
    usable = usable ^ 1;
    let { status, msg } = await popular.open({ id, usable });
    if (status) {
        ElMessage.success(msg);
        loadList();
    }
}
let AddDialogTable = ref(false);
//添加
let add = () => {
    AddDialogTable.value = true;
    form.value = {};
}
//编辑弹框
let dialogTableVisible = ref(false);
let edit = async (index) => {
    form.value = datas.value[index];
    dialogTableVisible.value = true;
}
// 保存修改
let save = async () => {
    let { status, msg } = await popular.edit(form.value);

    if (status) {
        dialogTableVisible.value=false;
        ElMessage.success(msg);
    }
}
// 保存添加
let saveAdd = async () => {
    let { status, msg } = await popular.add({ ...form.value });
    if (status) {
        ElMessage.success(msg);
    }
}
const rules = reactive({
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
        { min: 3, max: 5, message: '名字长度3到5', trigger: 'blur' },
    ],
    url: [
        { required: true, message: '请输入链接', trigger: 'blur' },
        { pattern: /^((ht|f)tps?):\/\/[\w\-]+(\.[\w\-]+)+([\w\-\.,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#])?$/, message: '请输入正确的链接' },
    ],
    target: [
        { required: true, message: '请输入邮箱' },
    ],
    slide_order: [{ required: true, message: '请输入排序' }],
})

// 删除
let remove = async (id) => {
    // console.log(id);
    let { status, msg } = await popular.remove({ id });
    if (status) {
        ElMessage.success(msg);
        loadList();
    } else {
        ElMessage.error(msg);
    }
}

// 添加token
let token = sessionStorage.token;
let headers = { Authorization: `Bearer ${token}` };
// 附加参数
let extra = { type: 'common' };
// 上传成功
const handleAvatarSuccess = ({ status, msg, src }, uploadFile) => {
    //如果上传成功
    if (status) {
        // 生成图片的地址
        form.value.picture = src;
        // form.avatar = URL.createObjectURL(uploadFile.raw);
        ElMessage.success(msg);
    } else {
        ElMessage.error(msg);
    }
}
// 上传失败
let handleUploadError = (error, uploadFile) => {
    let { status, msg } = JSON.parse(error.message);
    ElMessage.error(msg);
}
const handleBeforeUpload = (rawFile) => {
    // 判断图片格式/^imge\/(jpeg|png|jpg)$/
    let isValid = /^image\/(jpeg|png|jpg)$/.test(rawFile.type);
    if (!isValid) {
        ElMessage.error('头像必须是jpg/png格式!')
        return false
    }
    //图片大于2MB
    if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('头像体积不能大于2MB!')
        return false
    }
    return true
}

</script>
<style>
.card-header {
    width: 100%;
    display: flex;
    justify-content: space-between;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>